#!/usr/bin/env sh
function killByname() {
    pid=`ps -ef | grep $1 | awk '{print $2}'`
    echo pid=$pid
    if [ "$pid" != "" ];then
      kill -9 $pid
    fi
}

if [ "$1" == "fast" ]; then
  #rm build/emerald/src/pokemon.o
  make DINFO=1 -f fast.mk elf
elif [ "$1" == "fastn" ]; then
  make DINFO=1 -j$(nproc) NODEP=0
elif [ "$1" == "full" ]; then
  make -j$(nproc) DINFO=1
elif [ "$1" == "final" ]; then
  make -j$(nproc) MODERN=1
elif [ "$1" == "finalf" ]; then
  make -j$(nproc) MODERN=1  -f fast.mk elf
elif [ "$1" == "md" ]; then
  make -j$(nproc) MODERN=1 DINFO=1
elif [ "$1" == "mdf" ]; then
  make -j$(nproc) MODERN=1 DINFO=1 -f fast.mk elf
elif [ "$1" == "fastrun" ]; then
  make DINFO=1 -f fast.mk elf
  mgba --gdb pokeemerald.gba &
elif [ "$1" == "debug" ]; then
  killByname mgba
  mgba --gdb pokeemerald.gba &
elif [ "$1" == "run" ]; then
  killByname mgba
  mgba pokeemerald.gba &
elif [ "$1" == "debugm" ]; then
  killByname mgba
  mgba --gdb pokeemerald_modern.gba &
elif [ "$1" == "rd" ]; then
  if [ "$2" == "" ]; then
    echo "请输入版本号"
    exit 1
  fi
  if [ "$3" != "old" -a "$3" != "modern" ]; then
    echo "请输入正确的编译方式"
    exit 1
  fi
  if [ "$3" == "old" ]; then
    MODE="-j$(nproc) DINFO=1"
    NAME=pokeemerald.gba
  else
    MODE="-j$(nproc) DINFO=1 MODERN=1"
    NAME=pokeemerald_modern.gba
  fi
  echo "MODE="$MODE
  echo "NAME="$NAME
  sed -i 's/PROGRAM_DEBUG\s\+1/PROGRAM_DEBUG 0/g' include/battle_debug.h
#  python temp/randomKey.py "include/pokemon.h"
  sed -i 's/USE_BATTLE_DEBUG\s\+1/USE_BATTLE_DEBUG 0/g' include/battle_debug.h
  make $MODE
  python temp/fill.py ${NAME} ${NAME%.*}.elf gUnknown_08DE3FD4
  python temp/encr_softreset.py ${NAME} ${NAME%.*}.elf
  python temp/checksum.py ${NAME}
  cp $NAME "传说绿宝石$2.gba"
  sed -i 's/USE_BATTLE_DEBUG\s\+0/USE_BATTLE_DEBUG 1/g' include/battle_debug.h
  make $MODE
  python temp/fill.py ${NAME} ${NAME%.*}.elf gUnknown_08DE3FD4
  python temp/encr_softreset.py ${NAME} ${NAME%.*}.elf
  python temp/checksum.py ${NAME}
  cp $NAME "传说绿宝石$2 DEBUG版.gba"
  sed -i 's/PROGRAM_DEBUG\s\+0/PROGRAM_DEBUG 1/g' include/battle_debug.h
  echo "使用"$3"模式编译完成"
elif [ "$1" == "makedebug" ]; then
  sed -i 's/PROGRAM_DEBUG\s\+1/PROGRAM_DEBUG 0/g' include/battle_debug.h
  make -j$(nproc) DINFO=1
  sed -i 's/PROGRAM_DEBUG\s\+0/PROGRAM_DEBUG 1/g' include/battle_debug.h
  python temp/fill.py pokeemerald.gba pokeemerald.elf gUnknown_08DE3FD4
  python temp/encr_softreset.py pokeemerald.gba pokeemerald.elf
  python temp/checksum.py "pokeemerald.gba"
elif [ "$1" == "jpt" ]; then
  python temp/genTrainer.py j2p temp/party.json > src/data/trainer_parties.h
  python temp/genTrainer.py j2t temp/trainer.json > src/data/trainers.h
elif [ "$1" == test ]; then
  NAME=pokeemerald.gba
  echo python temp/fill.py ${NAME} ${NAME%.*}.elf gUnknown_08DE3FD4
fi

